package com.shenwei.yingdaoguanli.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shenwei.yingdaoguanli.entity.FileCleanLog;
import com.shenwei.yingdaoguanli.entity.FileStat;
import com.shenwei.yingdaoguanli.entity.dto.BackupLogDto;
import com.shenwei.yingdaoguanli.entity.dto.FileCleanLogDto;
import com.shenwei.yingdaoguanli.service.FileCleanLogService;
import com.shenwei.yingdaoguanli.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.shenwei.yingdaoguanli.mapper.FileCleanLogMapper;

import java.io.File;
import java.util.*;


/**
 * @Author wang
 * @Date 2025/1/8 22:45
 * @PackageName:com.shenwei.yingdaoguanli.service.impl
 * @ClassName: FileStatServiceImpl
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class FileCleanLogServiceImpl implements FileCleanLogService {

    @Autowired
    private FileCleanLogMapper fileCleanLogMapper;

    @Override
    public List<FileCleanLog> selectFileCleanLog(FileCleanLogDto fileCleanLogDto) {
        return fileCleanLogMapper.selectFileCleanLog(fileCleanLogDto);
    }


    @Override
    public boolean cleanFiles(String directoryPath, String fileType) {
        File directory = new File(directoryPath);
        validateDirectory(directory);

        // 收集要清理的文件
        List<File> filesToClean = collectFilesOfType(directory, fileType);

        // 按最底层文件夹分组
        Map<String, List<File>> filesGroupedByParent = groupFilesByParentDirectory(filesToClean);

        // 逐个清理并记录日志
        int totalCleanedCount = 0;
        for (Map.Entry<String, List<File>> entry : filesGroupedByParent.entrySet()) {
            String parentDirectoryPath = entry.getKey();
            List<File> filesInParent = entry.getValue();

            int cleanedCount = cleanFilesAndLog(filesInParent, parentDirectoryPath, fileType);
            totalCleanedCount += cleanedCount;
        }

        return totalCleanedCount > 0;
    }

    @Override
    public FileCleanLog selectFileCleanLogById(String id) {
        LambdaQueryWrapper<FileCleanLog> queryWrapper = new QueryWrapper<FileCleanLog>().lambda();
        queryWrapper.eq(FileCleanLog::getId, id);
        return fileCleanLogMapper.selectOne(queryWrapper);
    }

    private Map<String, List<File>> groupFilesByParentDirectory(List<File> filesToClean) {
        Map<String, List<File>> groupedFiles = new HashMap<>();
        for (File file : filesToClean) {
            String parentDirectory = file.getParent(); // 获取文件的父目录路径
            groupedFiles.computeIfAbsent(parentDirectory, k -> new ArrayList<>()).add(file);
        }
        return groupedFiles;
    }


    private int cleanFilesAndLog(List<File> filesToClean, String parentDirectoryPath, String fileType) {
        int cleanedCount = 0;
        StringBuilder deletedFileNames = new StringBuilder();

        for (File file : filesToClean) {
            if (file.delete()) {
                cleanedCount++;
                deletedFileNames.append(file.getName()).append("; ");
            }
        }

        if (cleanedCount > 0) {
            logCleanOperation(parentDirectoryPath, fileType, cleanedCount, deletedFileNames.toString());
        }

        return cleanedCount;
    }


    private void logCleanOperation(String parentDirectoryPath, String fileType, int cleanedCount, String deletedFileNames) {
        FileCleanLog cleanLog = new FileCleanLog();
        cleanLog.setFilePath(parentDirectoryPath); // 记录最底层文件夹路径
        cleanLog.setCleanType(fileType);
        cleanLog.setCleanTime(DateUtils.format(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS));
        cleanLog.setOperator("admin"); // 根据实际传入的操作人
        cleanLog.setCleanStatus("完成");
        cleanLog.setRemarks("清理操作完成，删除了 " + cleanedCount + " 个文件：" + deletedFileNames.trim());

        cleanLog.setCleanCount(cleanedCount); // 文件数量

        fileCleanLogMapper.insert(cleanLog);
    }



    private void validateDirectory(File directory) {
        if (!directory.exists() || !directory.isDirectory()) {
            throw new IllegalArgumentException("指定的路径无效！");
        }
    }

    // 递归查找指定类型的文件
    private List<File> collectFilesOfType(File directory, String fileType) {
        List<File> files = new ArrayList<>();
        Queue<File> directoriesQueue = new LinkedList<>();
        directoriesQueue.offer(directory);

        while (!directoriesQueue.isEmpty()) {
            File dir = directoriesQueue.poll();
            File[] fileList = dir.listFiles();

            if (fileList == null || fileList.length == 0) {
                continue; // 空目录跳过
            }

            for (File file : fileList) {
                if (file.isDirectory()) {
                    directoriesQueue.offer(file); // 如果是子目录，加入队列
                } else if (file.getName().endsWith(fileType)) {
                    files.add(file); // 如果是指定类型的文件，添加到列表
                }
            }
        }

        return files;
    }
}